package com.bai.localshop.runner;


import com.bai.localshop.mapper.ProductMapper;
import com.bai.localshop.pojo.entity.Product;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 应用启动时自动初始化布隆过滤器
 */
//@Component
@RequiredArgsConstructor
@Slf4j
public class BloomFilterInitRunner implements CommandLineRunner {

    private final RBloomFilter<String> createCachePenetrationBloomFilter;
    private final ProductMapper productMapper;

    @Override
    public void run(String... args) throws Exception {
        log.info("开始初始化布隆过滤器...");

        // 直接使用 MyBatis Plus 的查询方法，不依赖自定义方法
        List<Product> products = productMapper.selectList(new QueryWrapper<Product>().select("id"));

        if (products.isEmpty()) {
            log.warn("数据库中没有商品数据，跳过布隆过滤器初始化");
            return;
        }

        log.info("找到{}个商品，开始添加到布隆过滤器...", products.size());

        int successCount = 0;
        for (Product product : products) {
            try {
                boolean added = createCachePenetrationBloomFilter.add(product.getId().toString());
                if (added) {
                    successCount++;
                }
            } catch (Exception e) {
                log.error("添加商品ID到布隆过滤器失败: {}", product.getId(), e);
            }
        }

        log.info("布隆过滤器初始化完成，成功添加{}/{}个商品ID", successCount, products.size());

        // 简单验证
        if (!products.isEmpty()) {
            Long testId = products.get(0).getId();
            boolean exists = createCachePenetrationBloomFilter.contains(testId.toString());
            log.info("验证: 商品ID {} 在布隆过滤器中: {}", testId, exists);

            // 再多验证几个
            for (int i = 0; i < Math.min(3, products.size()); i++) {
                Long id = products.get(i).getId();
                boolean contains = createCachePenetrationBloomFilter.contains(id.toString());
                log.info("商品ID {} 在布隆过滤器中: {}", id, contains);
            }
        }
    }
}
